<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\CustomerInfo;
use App\Models\Referee;
use App\Models\RefereeBlack;
use App\Jobs\StatisticalRefereePoint;

//留资给推荐官发积分
class GivePointToRefereeForDrive implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $clue;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(CustomerInfo $customerInfo)
    {
        $this->clue = $customerInfo;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //没有试驾时间直接退出
        if (empty($this->clue->driver_at)) return true;

        //没有推荐官直接退出
        if (empty($this->clue->referee_id)) return true;

        $referee = Referee::where('user_id', $this->clue->referee_id)->first();
        //找不到推荐官直接退出
        if (is_null($referee)) return true;
        //推荐官被拉黑直接退出
        if (RefereeBlack::phoneExists($referee->phone)) return true;

        //非首次试驾不发积分
        if (CustomerInfo::where('user_id', $this->clue->user_id)->where('driver_point', '>', 0)->whereNotNull('referee_id')->exists()) return true;

        $series = $this->clue->vehicle->series;
        if ($series->recommend && $series->driver_point > 0) {
            app('App\Services\DfacService')->givePointToReferee($referee->user->weixin_unionid, 'dfjk-referee-drive', $series->driver_point);
            $this->clue->driver_point = $series->driver_point;
            $this->clue->save();
            //计算推荐获得积分数
            dispatch(new StatisticalRefereePoint($referee));
            return true;
        }

        loop:
        return true;
    }
}
